const config = require('../config')

// 获取当前环境的配置
const env = 'dev' // 这里可以根据实际情况切换环境
const currentConfig = config[env]

// 请求工具类
const request = (options) => {
  return new Promise((resolve, reject) => {
    const token = wx.getStorageSync('token')
    
    wx.request({
      url: `${currentConfig.apiBaseUrl}${options.url}`,
      method: options.method || 'GET',
      data: options.data,
      header: {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : ''
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else if (res.statusCode === 401) {
          // token失效，需要重新登录
          wx.navigateTo({
            url: '/pages/login/login'
          })
          reject(new Error('未登录或登录已过期'))
        } else {
          reject(new Error(res.data.message || '请求失败'))
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

module.exports = request